/**
 * Created by icyhy on 2017/5/22.
 */
"use strict";
var builder = require("../response/rest.result.builder.js");
var clanModel = require("../models/clan.js");
var clanChargeModel = require("../models/clan.charge");
const _ = require('lodash');

module.exports = {
  create: function(req, res, next) {
    var clanEntity = new clanModel(req.body);
    // var topicEnity = new clanModel({
    //   title: 'aaa',
    //   type: 'dd',
    //   ext: '.jpg',
    //   size: 1024,
    //   Content: 'dsf ',
    //   created: Date.now(),
    //   creater: 'dsfadf '
    //
    // });
    console.log(clanEntity)
    clanModel.create(clanEntity, function(err, clan) {
      if (err) return next(err);
      return builder.buildSuccessResultInfoWithData(res, clan);
    })
  },
  update: function(req, res, next) {
    var clanEntity = new clanModel(req.body);
    console.log(clanEntity)
    clanModel.update({_id:clanEntity._id.toString()}, clanEntity, function(err, clan) {
      if (err) return next(err);
      return builder.buildSuccessResultInfoWithData(res, clan);
    })
  },
  /**
   * 修改‘used’属性，启用或停用
   */
  enable:function(req, res, next){
    var id = req.params.id || '';
    var used = (parseInt(req.params.used, 0) || 0) == 0 ? false:true;
    clanModel.findOneAndUpdate({_id:id},{"used":used},function(err){
      if(err) return next(err);
      return builder.buildSuccessResultInfo(res);
    });

  },
  getList: function(req, res, next) {
    var pagesize = parseInt(req.query.pagesize, 50) || 50;
    var pagestart = parseInt(req.query.pagestart, 10) || 1;
    console.log(pagesize + "  " + pagestart);
    clanModel.find()
      .skip((pagestart - 1) * pagestart)
      .limit(pagesize).exec(function(err, clans) {
      if (err) return next(err);
      if (!clans) return next(new Error('clans not found'));

      return builder.buildSuccessResultInfoWithData(res, clans);
    });
  },

  getById: function(req, res, next) {
    if("undefined" == req.params.id || "undefined" == typeof req.params.id){
      console.error('getById() id undefined.')
      return
    }
    var id = req.params.id || '';
    console.log("id:" + id);
    clanModel.findOne({
      _id: id
    })
      .exec(function(err, clan) {
        if (err) return next(err);
        if (!clan) return next(new Error('not  found'));

        return builder.buildSuccessResultInfoWithData(res, clan);
      });
  },

  /**
   * 删除部落
   */
  deleteById:function(req, res, next){
    var id = req.params.id || '';
    clanModel.remove({ _id: id }, function (err) {
      if (err) return next(err);
      return builder.buildSuccessResultInfo(res);
    });
  },
  /**
   * 加入部落
   */
  joinClan: function(req, res, next) {
    var clanid = req.query.clanid;
    var userid = req.query.userid;
    var chargeamount = parseInt(req.query.chargeamount, 0) || 0;
    if(chargeamount == 0){
      return builder.buildBadRequestResult();
    }

    //更新部落中的用户列表
    clanModel.findOne({
      _id: clanid
    }).exec(function(err, clan) {
      if (err) return next(err);
      if (!clan) return next(new Error('not  found'));

      var users = clan.users;
      users.push(userid); //更新用户列表
      clanModel.findOneAndUpdate({"_id":clanid},{"users":users},function(err){
        if(err) return next(err);
        //用户列表更新成功
        //提交契约金
        var clanChargeEntity = new clanChargeModel({
          subjectId: clanid,//课题组id
          userId: userid,//提款用户id
          chargeAmount: chargeamount,//钱数
          created: Date.now()
        });
        console.log(clanChargeEntity);
        clanChargeModel.create(clanChargeEntity, function(err) {
          if (err) return next(err);
          return builder.buildSuccessResultInfo(res);
        });
      });
    });
  }
  ,
  /**
   * 退出部落
   */
  leaveClan: function (req, res, next) {
    var clanid = req.query.clanid;
    var userid = req.query.userid;
    //更新部落中的用户列表
    clanModel.findOne({
      _id: clanid
    })
      .exec(function(err, clan) {
        if (err) return next(err);
        if (!clan) return next(new Error('clan not  found'));

        var users = clan.users;
        _.remove(users, function(user){
          return user == userid;
        });
        //更新用户列表
        clanModel.findOneAndUpdate({"_id":clanid},{"users":users},function(err){
          if(err) return next(err);
          return builder.buildSuccessResultInfo(res);
        });
      });
  }
};
